<template>
    <div class="novelDetail-main">
        <div class="header-wrapper">
            <img :src="novelDetail.coverimg" :alt="novelDetail.name" class="header-bg">
            <div class="content">
                <i class="back-icon" @click="$router.go(-1)"></i>
                <div class="item">
                    <img :src="novelDetail.coverimg" :alt="novelDetail.name" onerror="this.src='https://static.kuaiyankanshu.net/';this.onerror=null" class="novel-icon">
                    <div class="right">
                        <p class="name">{{novelDetail.name}}</p>
                        <p>作者：{{novelDetail.author}}</p>
                        <p>分类：{{novelDetail.category}}</p>
                        <p>来源：read.qidian.com</p>
                        <p>更新：{{updateTime}}</p>
                    </div>
                </div>
                <div class="btn-wrapper">
                    <button class="enter" @click="editBookcase">{{isAddBookshelf?'移出书架':'加入书架'}}</button>
                    <nuxt-link :to="{path:'/read',query:{novelId:novelDetail.novelid,chapterId:'1',siteId:novelDetail.siteid}}"><button class="begin-read">开始阅读</button></nuxt-link>
                    <a href="https://kuaiyanapps.oss-cn-shenzhen.aliyuncs.com/download/index.html"><button class="app-read">TXT下载</button></a>
                </div>
            </div>
        </div>
        <div class="novel-introduction">
            <Introduction :desStr="novelDetail.intro" v-if="novelDetail.intro"></Introduction>
        </div>
        <div class="catalog-list">
            <p class="title">{{novelDetail.name}}最新章节</p>
            <ul>
                <li>
                  <router-link :to="{path:'/read',query:{novelId:item.novelid,chapterId:item.oid,cId:item.cId,siteId:item.siteid}}" v-for="(item,index) in novelDetail.last" :key="index" v-if="novelDetail.last.length">
                      <span class="list-item ellipsis">{{item.name}}</span><i class="icon"></i>
                  </router-link>
                </li>
                <li>
                  <router-link :to="{path:'/read/catalog',query:{novelId:novelDetail.novelId,siteId:novelDetail.siteid,name:novelDetail.name}}">
                      <span class="left">目录</span><span class="center">连载至{{lastChapter}}章 · {{updateTime}}更新</span><i class="icon"></i>
                  </router-link>
                </li>
            </ul>
        </div>
        <div class="hot-box">
            <p class="hot-title">热门推荐</p> 
            <div class="hot-list">
                <ul class="imgText-type clearfix">
                  <li>
                    <router-link :to="'/novelDetail/'+item.novelId" v-for="(item,index) in recentUpdate" :key="index">
                        <div class="list-item">
                            <div class="imges">
                                <img :src="item.cover" :alt="item.name" onerror="this.src='https://static.kuaiyankanshu.net/';this.onerror=null">
                            </div>
                            <p class="title ellipsis">{{item.name}}</p>
                            <p class="des ellipsis">{{item.author}}</p>
                        </div>
                    </router-link>
                  </li> 
                </ul>
            </div>
        </div>
        <div class="source-box">
            <p class="title">{{novelDetail.name}}来源更新</p>
            <ul>
                <li v-for="(item,index) in sourceListArr" :key="index">
                    <nuxt-link  :to="{path:'/read/catalog',query:{novelId:novelDetail.novelId,siteId:novelDetail.siteid,name:novelDetail.name}}">
                        <span class="novel-title">{{item.last}}</span><span class="source-name">{{item.sitename}}</span>
                    </nuxt-link>
                </li>
            </ul>
        </div>
        <div class="comment-box">
            <p class="title">{{novelDetail.name}}评论</p>
            <ul class="comment-list">
                <li v-for="(item,index) in commentList" :key="index">
                    <nuxt-link :to="'/novelDetail/'+$route.params.novelid">
                        <div class="left">
                            <img src="//static.kuaiyankanshu.net/public/image/noavatar.gif" alt="快眼看书">
                        </div>
                        <div class="right">
                            <span class="name">{{item.name}}</span><span class="time">{{timeFilter(item.datetime)}}</span>
                            <div class="content">
                               {{item.content}}
                            </div>
                        </div>
                    </nuxt-link>
                </li>
            </ul>
            <div class="nologin" v-if="!isLogin">
                请您 <nuxt-link to="/loginReg">注册</nuxt-link> 或 <nuxt-link to="/loginReg">登陆</nuxt-link> 之后再发布评论
            </div>
            <textarea v-model="commentContent" v-if="isLogin"></textarea>
            <button @click="addComment" v-if="isLogin">发布评论</button>
        </div>
        <Footer></Footer>
    </div>
</template>

<script>
import { Toast, MessageBox } from "mint-ui";
import api from "~/plugins/api.js";
import axios from "axios";
import qs from "qs";
import storage from "localforage";
import Introduction from "~/pages/read/introduction";
import Footer from "~/components/footer";
export default {
  head() {
    return {
      title: `${this.novelDetail.name}最新章节列表_${this.novelDetail.name}(${
        this.novelDetail.author
      })小说_${this.novelDetail.name}全文阅读_${
        this.novelDetail.name
      }无弹窗 - 快眼看书`,
      meta: [
        {
          name: "description",
          content: `快眼看书提供${this.novelDetail.category}小说《${
            this.novelDetail.name
          }》最新章节的搜索，更新超级快，无病毒无木马，页面干净清爽，希望大家收藏!`
        },
        {
          name: "keyWords",
          content: `${this.novelDetail.name}最新章节列表,${
            this.novelDetail.name
          }快眼看书`
        }
      ]
    };
  },
  data() {
    return {
      msg: "hehe",
      desStr:
        " 黎明时分，黑夜与白昼正在交接，浓雾中的大田镇还在熟睡，除了几个勤奋的猎户开始上山狩猎，偶尔几声鸡啼犬吠也没能惊扰大田镇的清梦，很快湮没在寂静中。依山吃山，靠水吃水，背靠着小屿山的大田镇名字中带着耕田的美好愿望，却因田地稀少和贫瘠而不得不世代狩猎。",
      novelDetail: {},
      bookshelfIdArr: [],
      isAddBookshelf: false,
      timeS: 1519788444,
      commentList: [],
      commentContent: '',
      sourceListArr: [],
      recentUpdate: [],
      isLogin: false
    };
  },
  computed: {
    updateTime: function() {
      if (this.novelDetail.lastupdate) {
        return this.common.formatMsgTime(this.novelDetail.lastupdate);
      }
    },
    lastChapter: function() {
      if (this.novelDetail.lastchaptername) {
        let lastArr = this.novelDetail.lastchaptername.split("章");
        if (lastArr.length) {
          let lastArr1 = lastArr[0].split("第");
          if (lastArr1.length) {
            return lastArr1[1];
          }
        }
      }
    }
  },
  created() {
    if (!process.server) {
      // 浏览器渲染
      this.initData();
      this.getCommentList();
      this.getSourceList();
      this.getRecentUpdate();
    }
  },
  mounted() {
    Array.prototype.remove = function(val) {
      var index = this.indexOf(val);
      if (index > -1) {
        this.splice(index, 1);
      }
    };
    if (this.novelDetail.novelid) {
      // 服务端渲染调用
      this.bookshelfAction();
    }
  },
  methods: {
    async initData() {
      let userInfo = await storage.getItem("userinfo");
      if (userInfo) {
          this.isLogin = true
      }else{
          this.isLogin = false
      }
      let paramsData = { novelId: this.$route.params.novelid };
      let result = await axios.get(api.novelDetails, { params: paramsData });
      let novelDetail = {};
      if (result) {
        novelDetail = result.data.data;
        this.isover = novelDetail.isover;
        this.novelDetail = novelDetail;
        this.bookshelfAction();
      }
    },
    /**
     * 判断是否有添加书架
     */
    async bookshelfAction() {
      let _this = this;
      this.bookshelfIdArr = (await storage.getItem("bookshelfIdKey")) || [];
      this.bookshelfIdArr.forEach(function(item) {
        if (item == _this.novelDetail.novelid) {
          _this.isAddBookshelf = true;
        }
      });
    },
    /**
     * 添加/移出书架
     */
    editBookcase() {
      if (this.isAddBookshelf) {
        // 移出
        MessageBox.confirm("是否移出书架?")
          .then(action => {
            this.deleteBookcase();
          })
          .catch(cancel => {});
      } else {
        // 添加
        this.addBookcase();
      }
    },
    /**
     * 加入书架
     */
    async addBookcase() {
      let userInfo = await storage.getItem("userinfo");
      if (userInfo) {
        let paramsData = {
          novelId: this.novelDetail.novelid,
          chapterId: "",
          uid: userInfo.uid,
          token: userInfo.token
        };
        let result = await axios.post(
          api.addBookcase,
          qs.stringify(paramsData)
        );
        if (result) {
          if (result.data.status == 1) {
            Toast("添加成功");
            let bookshelf = (await storage.getItem("bookshelfIdKey")) || [];
            bookshelf.remove(this.novelDetail.novelid);
            bookshelf.unshift(this.novelDetail.novelid);
            storage.setItem("bookshelfIdKey", bookshelf);
          }
        }
      } else {
        Toast("添加成功");
        this.bookshelfIdArr.remove(this.novelDetail.novelid);
        this.bookshelfIdArr.unshift(this.novelDetail.novelid);
        storage.setItem("bookshelfIdKey", this.bookshelfIdArr);
      }
      this.isAddBookshelf = true;
    },
    async deleteBookcase() {
      let userInfo = await storage.getItem("userinfo");
      let paramsData = {};
      if (userInfo) {
        paramsData = {
          novel_id: this.novelDetail.novelid,
          token: userInfo.token,
          uid: userInfo.uid
        };
        let result = await axios.post(
          api.deleteNovel,
          qs.stringify(paramsData)
        );
        if (result) {
          Toast(result.data.info);
          this.bookshelfIdArr.remove(this.novelDetail.novelid);
          storage.setItem("bookshelfIdKey", this.bookshelfIdArr);
        }
      } else {
        this.bookshelfIdArr.remove(this.novelDetail.novelid);
        storage.setItem("bookshelfIdKey", this.bookshelfIdArr);
      }
      this.isAddBookshelf = false;
    },
    async getCommentList() {
        let paramsData = { novelId: this.$route.params.novelid };
        let data = await  axios.get(api.commentList, {
           params: paramsData,
        })
        this.commentList = data.data.data
    },
    async addComment () {
        let userInfo = await storage.getItem("userinfo");
        if (userInfo) {
            var paramsData = {
                typeId: this.$route.params.novelid,
                token: userInfo.token,
                uid: userInfo.uid,
                content: this.commentContent
            }
        }else{
            Toast('请先登录！')
            return
        }
         let result = await axios.post(api.addComment,qs.stringify(paramsData))
         if(result){
             if(result.data.status==1){
                 Toast(result.data.data)
                 this.commentContent = ''
                 this.getCommentList()
             }else{
                 Toast(result.data.info)
             }
         }
    },
    async getSourceList() {
        let res = await axios.get(api.sourceList,{params:{novelId: this.$route.params.novelid}})
        if(res){
            this.sourceListArr = res.data.data
        }
        
    },
    async getRecentUpdate() {
        let res = await axios.get(api.choice,)
        if(res){
            this.recentUpdate = res.data.data.recentUpdate
        }
        
    },
    timeFilter: function (value) {
        return this.common.formatDateTime(value);
    },
  },
  async asyncData(content) {
    if (process.server) {
        let paramsData = { novelId: content.params.novelid };

        let [novelDetail,commentList,sourceList,choice] = await axios.all([
            axios.get(api.novelDetails, { params: paramsData }),
            axios.get(api.commentList, { params: paramsData }),
            axios.get(api.sourceList, { params: paramsData }),
            axios.get(api.choice)
        ])
        return { 
            novelDetail: novelDetail.data.data,
            commentList: commentList.data.data,
            sourceListArr: sourceList.data.data,
            recentUpdate: choice.data.data.recentUpdate,
            bookshelfIdArr: []
        }
    }else{
        return { 
            novelDetail: {},
        }
    }
  },
  components: {
    Introduction,
    Footer
  }
};
</script>
